<template>
  <div>
    <!--卡片视图区域-->
    <el-row>
      <el-card>
        <!--查询条件表单区域-->
        <el-row>
          <el-form :inline="true" label-position="left" :model="queryForm">
            <el-form-item v-model="queryForm.experimentName" label="课程及实验名称" size="small">
              <el-cascader ref="selectExperiment" size="small" style="width: 450px" :options="courseExperimentList"
                           :show-all-levels="true"></el-cascader>
            </el-form-item>
              <el-button type="primary" @click="onSubmit" size="small">查询</el-button>
          </el-form>
        </el-row>
        <!-- 标签页 区分报告类型-->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!--实验报告-->
          <el-tab-pane label="实验报告" name="first">
            <!--数据表格区域-->
            <el-table
              :data="reportList" border stripe>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="username" label="姓名" width="150px"></el-table-column>
              <el-table-column prop="stuId" label="学号" width="150px"></el-table-column>
              <el-table-column prop="status" label="状态" width="100px">
                <template v-slot:default="scope">
                  <el-tag type="warning" v-if="scope.row.status === '2'">
                    未批阅
                  </el-tag>
                  <el-tag type="success" v-if="scope.row.status === '3'">
                    已批阅
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="reportScore" label="评分" width="100px">
                <template v-slot:default="scope">
                  <div v-if="scope.row.reportScore === null || scope.row.reportScore === ''">
                    暂无评分
                  </div>
                  {{ scope.row.reportScore }}
                </template>
              </el-table-column>
              <el-table-column prop="reportTime" label="提交日期" width="180px"></el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-tooltip effect="dark" content="批改" placement="top" :enterable="false">
                    <el-button @click="markReport(scope.row,1)" type="primary"
                               icon="el-icon-edit-outline" size="small"></el-button>
                    <!--                           :disabled="scope.row.canApply === 0"-->
                  </el-tooltip>
                  <el-tooltip effect="dark" content="退回" placement="top"
                              :enterable="false">
                    <el-button @click="backReport(scope.row)" type="danger"
                               icon="el-icon-circle-close"
                               size="small"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!--预习报告-->
          <el-tab-pane label="预习报告" name="second">
            <!--数据表格区域-->
            <el-table
              :data="reportList" border stripe>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="username" label="姓名" width="150px"></el-table-column>
              <el-table-column prop="stuId" label="学号" width="150px"></el-table-column>
              <el-table-column prop="status" label="状态" width="100px">
                <template v-slot:default="scope">
                  <el-tag type="warning" v-if="scope.row.status === '2'">
                    未批阅
                  </el-tag>
                  <el-tag type="success" v-if="scope.row.status === '3'">
                    已批阅
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="评分" width="100px">
                <template v-slot:default="scope">
                  <div v-if="scope.row.score === null || scope.row.score === ''">
                    暂无评分
                  </div>
                  {{ scope.row.score }}
                </template>
              </el-table-column>
              <el-table-column prop="reportTime" label="提交日期" width="180px"></el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-tooltip effect="dark" content="批改" placement="top" :enterable="false">
                    <el-button @click="markReport(scope.row,2)" type="primary"
                               icon="el-icon-edit-outline" size="small"></el-button>
                    <!--                           :disabled="scope.row.canApply === 0"-->
                  </el-tooltip>
                  <el-tooltip effect="dark" content="退回" placement="top"
                              :enterable="false">
                    <el-button @click="backReport(scope.row)" type="danger"
                               icon="el-icon-circle-close"
                               size="small"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <!--验收报告-->
          <el-tab-pane label="验收报告" name="third">
            <!--数据表格区域-->
            <el-table
              :data="reportList" border stripe>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="username" label="姓名" width="150px"></el-table-column>
              <el-table-column prop="stuId" label="学号" width="150px"></el-table-column>
              <el-table-column prop="status" label="状态" width="100px">
                <template v-slot:default="scope">
                  <el-tag type="warning" v-if="scope.row.status === '2'">
                    未批阅
                  </el-tag>
                  <el-tag type="success" v-if="scope.row.status === '3'">
                    已批阅
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="评分" width="100px">
                <template v-slot:default="scope">
                  <div v-if="scope.row.score === null || scope.row.score === ''">
                    暂无评分
                  </div>
                  {{ scope.row.score }}
                </template>
              </el-table-column>
              <el-table-column prop="reportTime" label="提交日期" width="180px"></el-table-column>
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-tooltip effect="dark" content="批改" placement="top" :enterable="false">
                    <el-button @click="markReport(scope.row,3)" type="primary"
                               icon="el-icon-edit-outline" size="small"></el-button>
                    <!--                           :disabled="scope.row.canApply === 0"-->
                  </el-tooltip>
                  <el-tooltip effect="dark" content="退回" placement="top"
                              :enterable="false">
                    <el-button @click="backReport(scope.row)" type="danger"
                               icon="el-icon-circle-close"
                               size="small"></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-row>
    <!-- pdf 区域-->
    <el-row>
      <el-card v-if="markVisual">
        <!--进度条-->
        <el-row>
          <el-progress :percentage="Math.round(loadedRatio*100)" :format="format"></el-progress>
        </el-row>
        <!--PDF-->
        <el-row>
          <pdf
            :page="pageNum"
            :src="reportUrl"
            @progress="loadedRatio = $event"
            @num-pages="pageTotalNum=$event"
          ></pdf>
        </el-row>
        <!--翻页按钮-->
        <el-row>
          <div style="margin-top: 10px; color: #409EFF">{{ pageNum }} / {{ pageTotalNum }}</div>
          <el-button-group>
            <el-button type="primary" icon="el-icon-arrow-left" size="mini" @click="prePage">上一页</el-button>
            <el-button type="primary" size="mini" @click="nextPage">下一页<i
              class="el-icon-arrow-right el-icon--right"></i>
            </el-button>
          </el-button-group>
        </el-row>
        <el-row>
          <el-form inline :model="evaluateForm" ref="numberValidateForm" :rules="evaluateFormRules">
            <el-row>
              <el-form-item label="评语" prop="evaluation">
                <el-input type="textarea" size="small" v-model="evaluateForm.evalue"></el-input>
              </el-form-item>
              <el-form-item label="分数" prop="reportScore">
                <el-input size="small" v-model.number="evaluateForm.reportScore" autocomplete="off"></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm()">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-row>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  components: {
    pdf
  },
  data () {
    const checkScore = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('分数不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (value < 0) {
            callback(new Error('分数不能小于0'))
          } else if (value > 100) {
            callback(new Error('分数不能超过100'))
          } else {
            callback()
          }
        }
      }, 100)
    }
    return {
      // pdf 相关
      markVisual: false,
      reportUrl: '',
      pageNum: 1,
      // 评分表单
      evaluateForm: {
        id: '',
        reportScore: '',
        evalue: ''
      },
      evaluateFormRules: {
        reportScore: [
          {
            validator: checkScore,
            trigger: 'blur'
          }]
      },
      // 总页数
      pageTotalNum: 1,
      // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了
      loadedRatio: 0,
      activeName: 'first',
      queryForm: {
        courseName: '',
        experimentName: ''
      },
      courseExperimentList: [],
      reportList: []
    }
  },
  created () {
    this.getCourseExperimentList()
  },
  methods: {
    async getCourseExperimentList () {
      const { data: res } = await this.$http.post('/getExperimentByTeacherId')
        .catch((error) => {
          console.log(error)
          this.$message.error('网络连接超时')
        })
      if (res.status !== 200) {
        this.$message.error('获取课程信息失败')
      } else {
        // console.log(res.data.courseExperiments)
        this.courseExperimentList = res.data.courseAndExperimentStr
        this.total = res.data.total
      }
    },
    async getReportListByExperId () {
      const { data: res } = await this.$http.post('/getCommittedReportListByExperId',
        { experId: this.$refs.selectExperiment.getCheckedNodes()[0].data.value })
        .catch((error) => {
          console.log(error)
          this.$message.error('网络连接超时')
        })
      if (res.status !== 200) {
        this.$message.error('获取报告信息失败')
      } else {
        this.reportList = res.data.reports
        if (this.reportList.length === 0) {
          this.$message.info('该实验暂无学生提交报告')
        } else {
          this.$message.success('获取报告信息成功')
        }
        // console.log(this.reportList)
      }
    },
    onSubmit () {
      // console.log(this.$refs.selectExperiment.getCheckedNodes()[0].data.value)
      this.getReportListByExperId()
    },
    // 批改报告
    markReport (report, type) {
      this.markVisual = !this.markVisual
      this.evaluateForm.id = report.id
      this.evaluateForm.reportScore = parseInt(report.reportScore)
      this.evaluateForm.evalue = report.evalue
      if (type === 1) {
        this.reportUrl = report.reportFile
      } else if (type === 2) {
        this.reportUrl = report.previewFile
      } else {
        this.reportUrl = report.acceptanceFile
      }
      this.getNumPages()
    },
    handleClick (tab, event) {
      console.log(tab, event)
    },
    // 计算pdf页码总数
    getNumPages () {
      const loadingTask = pdf.createLoadingTask(this.reportUrl)
      loadingTask.promise.then(pdf => {
        this.numPages = pdf.numPages
      }).catch(err => {
        console.error('pdf 加载失败', err)
      })
    },
    // 上一页
    prePage () {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },
    // 下一页
    nextPage () {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },
    // 进度条
    format (percentage) {
      return percentage === 100 ? '加载进度：100%' : `加载进度：${percentage}%`
    },
    // 评分
    submitForm () {
      this.$refs.numberValidateForm.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/markReport', this.evaluateForm)
          .catch((error) => {
            console.log(error)
            this.$message.error('网络连接超时')
          })
        if (res.status === 401) {
          this.$message.error(res)
          await this.$router.push('/login')
        }
        if (res.status !== 200) this.$message.error(res.data.msg)
        if (res.status === 200) {
          this.$message.success(res.data.msg)
          this.markVisual = !this.markVisual
          await this.getReportListByExperId()
        }
      })
    },
    resetForm () {
      this.$refs.numberValidateForm.resetFields()
    }
  }
}
</script>

<style scoped>

</style>
